'use client';

import { useEffect, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import MobileLayout from '../../../components/layout/MobileLayout';
import { useSocket, Group, User } from '../../../context/SocketContext';
import styles from './page.module.css';

export default function GroupPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const groupId = searchParams.get('id');
  const mode = searchParams.get('mode') || 'view'; // view, create
  
  const {
    currentUser,
    groups,
    friends,
    getGroupMembers,
    groupMembers,
    createGroup,
    leaveGroup
  } = useSocket();
  
  const [group, setGroup] = useState<Group | null>(null);
  const [groupName, setGroupName] = useState('');
  const [selectedFriends, setSelectedFriends] = useState<string[]>([]);
  
  // 获取群组信息
  useEffect(() => {
    if (groupId && mode === 'view') {
      const foundGroup = groups.find(g => g.id === groupId);
      if (foundGroup) {
        setGroup(foundGroup);
        getGroupMembers(groupId);
      }
    }
  }, [groupId, mode, groups, getGroupMembers]);
  
  // 处理返回
  const handleBack = () => {
    router.push('/message');
  };
  
  // 处理好友选择
  const handleFriendSelect = (friendId: string) => {
    setSelectedFriends(prev => {
      if (prev.includes(friendId)) {
        return prev.filter(id => id !== friendId);
      } else {
        return [...prev, friendId];
      }
    });
  };
  
  // 处理创建群组
  const handleCreateGroup = () => {
    if (groupName.trim() && selectedFriends.length > 0) {
      createGroup(groupName, selectedFriends);
      router.push('/message');
    }
  };
  
  // 处理退出群组
  const handleLeaveGroup = () => {
    if (groupId) {
      leaveGroup(groupId);
      router.push('/message');
    }
  };
  
  // 处理开始聊天
  const handleStartChat = () => {
    if (group) {
      router.push(`/message/chat?id=${group.id}&type=group&name=${group.name}&avatar=${encodeURIComponent(group.avatar)}`);
    }
  };
  
  if (mode === 'view' && !groupId) {
    return <div>无效的群组ID</div>;
  }
  
  return (
    <MobileLayout>
      <div className={styles.groupPage}>
        {/* 头部 */}
        <div className={styles.header}>
          <div className={styles.backButton} onClick={handleBack}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M20 11H7.83L13.42 5.41L12 4L4 12L12 20L13.41 18.59L7.83 13H20V11Z" fill="#333"/>
            </svg>
          </div>
          <div className={styles.headerTitle}>
            {mode === 'view' ? '群组信息' : '创建群组'}
          </div>
        </div>
        
        {/* 查看模式 - 群组信息 */}
        {mode === 'view' && group && (
          <>
            <div className={styles.groupInfo}>
              <div className={styles.groupAvatar}>
                <Image 
                  src={group.avatar || '/avatars/group.svg'} 
                  alt={group.name} 
                  width={80} 
                  height={80} 
                  className={styles.avatarLarge}
                />
              </div>
              <div className={styles.groupName}>
                {group.name}
              </div>
              <div className={styles.groupMemberCount}>
                {groupMembers.length}人
              </div>
            </div>
            
            <div className={styles.membersList}>
              <div className={styles.membersHeader}>
                <div className={styles.membersTitle}>群组成员</div>
                <div className={styles.membersCount}>{groupMembers.length}</div>
              </div>
              
              <div className={styles.membersGrid}>
                {groupMembers.map((member) => (
                  <div key={member.id} className={styles.memberItem}>
                    <div className={styles.memberAvatar}>
                      <Image 
                        src={member.avatar} 
                        alt={member.username} 
                        width={50} 
                        height={50} 
                        className={styles.avatar}
                      />
                    </div>
                    <div className={styles.memberName}>
                      {member.username}
                    </div>
                  </div>
                ))}
              </div>
            </div>
            
            <div className={styles.actionButtons}>
              <button className={styles.primaryButton} onClick={handleStartChat}>
                发送消息
              </button>
              <button className={styles.dangerButton} onClick={handleLeaveGroup}>
                退出群组
              </button>
            </div>
          </>
        )}
        
        {/* 创建模式 - 创建群组 */}
        {mode === 'create' && (
          <>
            <div className={styles.createGroupForm}>
              <div className={styles.formGroup}>
                <label className={styles.formLabel}>群组名称</label>
                <input 
                  type="text" 
                  className={styles.formInput}
                  placeholder="请输入群组名称"
                  value={groupName}
                  onChange={(e) => setGroupName(e.target.value)}
                />
              </div>
              
              <div className={styles.formGroup}>
                <label className={styles.formLabel}>选择好友</label>
                <div className={styles.friendsList}>
                  {friends.map((friend) => (
                    <div 
                      key={friend.id} 
                      className={`${styles.friendItem} ${selectedFriends.includes(friend.id) ? styles.friendSelected : ''}`}
                      onClick={() => handleFriendSelect(friend.id)}
                    >
                      <div className={styles.friendAvatar}>
                        <Image 
                          src={friend.avatar} 
                          alt={friend.username} 
                          width={50} 
                          height={50} 
                          className={styles.avatar}
                        />
                      </div>
                      <div className={styles.friendInfo}>
                        <div className={styles.friendName}>{friend.username}</div>
                        <div className={styles.friendStatus}>
                          {friend.online ? '在线' : '离线'}
                        </div>
                      </div>
                      <div className={styles.friendCheckbox}>
                        {selectedFriends.includes(friend.id) && (
                          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M9 16.17L4.83 12L3.41 13.41L9 19L21 7L19.59 5.59L9 16.17Z" fill="#2b7efb"/>
                          </svg>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            
            <div className={styles.actionButtons}>
              <button 
                className={`${styles.primaryButton} ${!groupName.trim() || selectedFriends.length === 0 ? styles.disabledButton : ''}`}
                onClick={handleCreateGroup}
                disabled={!groupName.trim() || selectedFriends.length === 0}
              >
                创建群组
              </button>
            </div>
          </>
        )}
      </div>
    </MobileLayout>
  );
}